import com.mysql.cj.jdbc.MysqlDataSource;

import javax.sql.DataSource;
import javax.xml.crypto.Data;
import java.awt.desktop.SystemEventListener;
import java.awt.dnd.DropTarget;
import java.sql.Connection;
import java.sql.ParameterMetaData;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.Scanner;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 19182
 * Date: 2025-08-19
 * Time: 19:16
 */
class DBUtil{   //单例模式连接数据库, 这样每个线程用的都是一个数据库
    private static volatile DataSource dataSource = null;
    public static DataSource getInsetance(){
        if(dataSource == null){ //如果初始化连接数据库成功, 就不需要再加锁执行创建数据库, 直接返回数据库即可
            synchronized (DBUtil.class){
                if(dataSource == null) {
                    MysqlDataSource ds = new MysqlDataSource(); //不能直接赋值给dataSource, 万一因为线程调度到新线程, 结果第一个if判断数据库变量不为空, 那么直接返回数据库, 可是实际上还没构建数据库连续属性
                    ds.setURL("jdbc:mysql://127.0.0.1:3306/java117?characterEncoding=utf8&useSSL=false");
                    ds.setUser("root");
                    ds.setPassword("201754ljj");
                    dataSource = ds;
                }
            }
        }
        return dataSource;
    }
}
public class jdbc {
    public static void main(String[] args) throws SQLException {
        Scanner scanner = new Scanner(System.in);
        DataSource dataSource = DBUtil.getInsetance();
        //连接数据库
        Connection connection = dataSource.getConnection();
        //构造SQL语句
        String sql = "insert into student values(?, ?)";
        System.out.println("请输入id:");
        int id = scanner.nextInt();
        System.out.println("请输入name:");
        String name = scanner.next();
        // 预处理sql语句
        PreparedStatement preparedStatement = connection.prepareStatement(sql);
        preparedStatement.setInt(1, id);
        preparedStatement.setString(2, name);
        int n = preparedStatement.executeUpdate();
        System.out.println(n);
        //关闭连接资源
        preparedStatement.close();
        connection.close();


    }
}
